import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
Vue.use(Router)

import articleRouter from '@/router/modules/article'
import articleShowRouter from '@/router/modules/articleShow'
const routes = [
  {
    path: '/',
    component: () => import('@/views/layout/index'),
    meta: {
      title: '一部手机游临泽',
    },
    children: [
      {
        path: '/',
        component: () => import('@/views/index'),
        meta: {
          title: '一部手机游临泽',
        },
      },
    ],
  },
  articleRouter,
  articleShowRouter,
  {
    path: '*',
    redirect: '/404',
  },
  {
    name: '404',
    component: () => import('@/views/error/404'),
    meta: {
      title: '未找到',
    },
  },
]

// add route path
routes.forEach(route => {
  route.path = route.path || '/' + (route.name || '')
})

const createRouter = () =>
  new Router({
    mode: 'hash', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes,
  })
const router = createRouter()

const resetRouter = () => {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

router.beforeEach((to, from, next) => {
  const title = to.meta && to.meta.title
  if (title) {
    document.title = title
  }
  if (to.matched.some(record => record.meta.auth)) {
    if (!store.state.user.token && to.fullPath.indexOf('/auth/') === -1) {
      store.commit('user/SET_AUTH_TO', to.fullPath)
      next({
        path: '/auth/login',
      })
    } else {
      next()
    }
  } else if (store.state.user.token && to.fullPath.indexOf('/auth/') === 0) {
    // 已登录， 进入登录前的页面
    const routerTo = store.state.user.authTo
    if (routerTo !== from.fullPath) {
      next({
        path: routerTo,
      })
    }
  } else {
    next()
  }
})

export { router, resetRouter }
